package 职责链.Demo2;

public abstract class Handler {

    protected Handler successor = null;
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public final void handle() {
        boolean handled = doHandle();
        if(this.successor != null && !handled) {
            successor.handle();
        }
    }

    // 将具体业务逻辑抽象到doHandle()方法中
    protected abstract boolean doHandle();
}

class HandlerA extends Handler {

    @Override
    protected boolean doHandle() {
        return false;
    }
}

class HandlerB extends Handler {

    @Override
    protected boolean doHandle() {
        return false;
    }
}

class HandlerChain {
    private Handler head;
    private Handler tail;

    public void addHandler(Handler handler) {
        if(head == null) {
            this.head = handler;
            this.tail = handler;
            return;
        }
        this.tail.setSuccessor(handler);
        this.tail = handler;
    }

    public void handle() {
        if(head != null) {
            head.handle();
        }
    }
}
